package com.newlink.building.common_base.widget

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.RadioButton
import com.newlink.building.common_base.R


/**
 * Created by xiaodong on 2024/11/1.
 */
@SuppressLint("AppCompatCustomView")
class MyRadioButton(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    RadioButton(context, attrs, defStyleAttr) {
    private var mDrawableSize = 0 //drawable大小

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    init {
        var drawableLeft: Drawable? = null
        var drawableRight: Drawable? = null
        var drawableBottom: Drawable? = null
        var drawableTop: Drawable? = null

        val a: TypedArray =
            context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton) //获取自定义属性
        val n = a.indexCount
        for (i in 0 until n) {
            val attr = a.getIndex(i)
            when (attr) {
                R.styleable.MyRadioButton_drawableSizes -> mDrawableSize = a.getDimensionPixelSize(
                    R.styleable.MyRadioButton_drawableSizes,
                    50
                ) //获取drawable大小，没设置时默认为50dp
                R.styleable.MyRadioButton_drawableTop -> drawableTop =
                    a.getDrawable(attr) //获取显示在上方的drawable
                R.styleable.MyRadioButton_drawableBottom -> drawableBottom =
                    a.getDrawable(attr) //获取显示在下方的drawable
                R.styleable.MyRadioButton_drawableRight -> drawableRight =
                    a.getDrawable(attr) //获取显示在右方的drawable
                R.styleable.MyRadioButton_drawableLeft -> drawableLeft =
                    a.getDrawable(attr) //获取显示在左方的drawable
                else -> {}
            }
        }
        a.recycle()
        setCompoundDrawablesWithIntrinsicBounds(
            drawableTop,
            drawableBottom,
            drawableLeft,
            drawableRight
        ) //调用重写的方法进行设置drawable的大小.
    }


    //重写TextView中的setCompoundDrawablesWithIntrinsicBounds的方法
    override fun setCompoundDrawablesWithIntrinsicBounds(
        top: Drawable?,
        bottom: Drawable?,
        left: Drawable?,
        right: Drawable?,
    ) {
        left?.setBounds(0, 0, mDrawableSize, mDrawableSize)
        right?.setBounds(0, 0, mDrawableSize, mDrawableSize)
        top?.setBounds(0, 0, mDrawableSize, mDrawableSize)
        bottom?.setBounds(0, 0, mDrawableSize, mDrawableSize)
        setCompoundDrawables(left, top, right, bottom) //设置完了bounds就可以调用这个方法进行设置了 不用在代码中进行动态控制了。
    }
}